package com.socket.client.util;

import cn.hutool.core.net.NetUtil;
import cn.hutool.http.useragent.Platform;
import cn.hutool.http.useragent.UserAgentParser;
import com.socket.client.model.chat.UserExt;
import io.netty.handler.codec.http.HttpHeaderNames;
import io.netty.handler.codec.http.HttpHeaders;

/**
 * Netty 工具类
 */
public class NettyUtil {
    private static final String[] headerNames = {
            "X-Forwarded-For",
            "X-Real-IP",
            "Proxy-Client-IP",
            "WL-Proxy-Client-IP",
            "HTTP_CLIENT_IP",
            "HTTP_X_FORWARDED_FOR"
    };

    /**
     * 获取客户端真实IP地址
     */
    public static String getClientIP(HttpHeaders headers) {
        String ip;
        for (String header : headerNames) {
            ip = headers.get(header);
            if (!NetUtil.isUnknown(ip)) {
                return NetUtil.getMultistageReverseProxyIp(ip);
            }
        }
        ip = headers.get(HttpHeaderNames.HOST);
        return NetUtil.getMultistageReverseProxyIp(ip);
    }

    /**
     * 获取当前登录平台
     */
    public static String getPlatform(HttpHeaders headers) {
        String header = headers.get(HttpHeaderNames.USER_AGENT);
        Platform platform = UserAgentParser.parse(header).getPlatform();
        return platform.isAndroid() ? "手机" : platform.isIos() ? "iPhone" : "PC";
    }

    /**
     * 获取登录令牌
     */
    public static String getToken(HttpHeaders headers) {
        return headers.get(HttpHeaderNames.SEC_WEBSOCKET_PROTOCOL);
    }

    /**
     * 获取扩展用户信息
     *
     * @param headers 请求头
     * @return {@link UserExt}
     */
    public static UserExt getExtUser(HttpHeaders headers) {
        UserExt ext = new UserExt();
        ext.setToken(NettyUtil.getToken(headers));
        ext.setClientIp(NettyUtil.getClientIP(headers));
        return ext;
    }
}
